import {Mat4, Vec3} from "../../../src/math";

const _float16 = new Float32Array(16);

export class Shader{
    uniforms:{[key:string]:WebGLUniformLocation}= {};
    attribs:{[key:string]:GLint} = {};
    public constructor(
        public gl:WebGL2RenderingContext,
        public program:WebGLProgram) {}


    public createUniforms(uniformNames:string[]) {
        let gl = this.gl;
        uniformNames.forEach(name => {
            let location = gl.getUniformLocation(this.program, name);
            if (!location) {
                throw `getUniformLocation for ${name} failed!`;
            }
            this.uniforms[name] = location;
        });
    }

    public createAttribs(attribs:string[]) {
        let gl = this.gl;
        attribs.forEach(name => {
            let location = gl.getAttribLocation(this.program, name);
            if (location < 0) {
                throw `getAttribLocation for ${name} failed!`;
            }
            this.attribs[name] = location;
        });
    }

    public bind(){
        this.gl.useProgram(this.program);
    }
    public unbind(){
        this.gl.useProgram(null);
    }

    public setMat4(name:string,m4:Mat4){
        Mat4.toArray(_float16,m4);
        this.gl.uniformMatrix4fv(this.uniforms[name],false,_float16);
        return this;
    }

    public setVec3(name:string,v3:Vec3){
        this.gl.uniform3f(this.uniforms[name],v3.x,v3.y,v3.z);
        return this;
    }
}
